# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import time
from typing import List
from tortoise.queryset import Q
from hypertext import PagingResult
from common.utils.urls import UrlUtil
from common.utils.times import TimeUtil
from common.models.public import SquareCategoryModel
from apps.admin.schemas.square import category_schema as schema


class SquareCategoryService:

    @classmethod
    async def whole(cls, params: schema.SquareCategorySearchIn) -> List[schema.SquareCategoryListVo]:
        where = SquareCategoryModel.build_search({
            "%like%": ["name"],
            "=": ["is_disable"]
        }, params.__dict__)

        lists = await (SquareCategoryModel
                       .filter(*where)
                       .filter(scene=params.type)
                       .filter(is_delete=0)
                       .order_by("-sort", "-id")
                       .all())

        _lists = []
        for item in lists:
            _lists.append(schema.SquareCategoryListVo(
                id=item.id,
                name=item.name,
                scene=item.scene,
                icon=item.icon,
                nums=0,
                sort=item.sort,
                is_disable=item.is_disable,
                create_time=TimeUtil.timestamp_to_date(item.create_time),
                update_time=TimeUtil.timestamp_to_date(item.update_time)
            ))

        return _lists

    @classmethod
    async def lists(cls, params: schema.SquareCategorySearchIn) -> PagingResult[schema.SquareCategoryListVo]:
        where = SquareCategoryModel.build_search({
            "%like%": ["name"],
            "=": ["is_disable"]
        }, params.__dict__)

        where.append(Q(scene=params.type))
        where.append(Q(is_delete=0))

        if params.is_disable is not None:
            where.append(Q(is_disable=params.is_disable))

        _model = SquareCategoryModel.filter(*where).order_by("-id")
        _pager = await SquareCategoryModel.paginate(
            model=_model,
            page_no=params.page_no,
            page_size=params.page_size,
            fields=SquareCategoryModel.without_field("is_delete,delete_time"),
            schema=schema.SquareCategoryListVo
        )
        for item in _pager.lists:
            item.icon = await UrlUtil.to_absolute_url(item.icon)
        return _pager

    @classmethod
    async def detail(cls, id_: int) -> schema.SquareCategoryDetailVo:
        detail = await SquareCategoryModel.filter(id=id_).get()
        return schema.SquareCategoryDetailVo(
            id=detail.id,
            scene=detail.scene,
            name=detail.name,
            sort=detail.sort,
            is_disable=detail.is_disable
        )

    @classmethod
    async def add(cls, post: schema.SquareCategoryAddIn):
        await SquareCategoryModel.create(
            scene=post.scene,
            name=post.name,
            sort=post.sort,
            is_disable=post.is_disable,
            create_time=int(time.time()),
            update_time=int(time.time())
        )

    @classmethod
    async def edit(cls, post: schema.SquareCategoryEditIn):
        await SquareCategoryModel.filter(id=post.id, is_delete=0).get()
        await SquareCategoryModel.filter(id=post.id).update(
            name=post.name,
            icon=UrlUtil.to_relative_url(post.icon),
            sort=post.sort,
            is_disable=post.is_disable,
            update_time=int(time.time())
        )

    @classmethod
    async def delete(cls, id_: int):
        await SquareCategoryModel.filter(id=id_, is_delete=0).get()
        await SquareCategoryModel.filter(id=id_).update(
            sort="",
            is_delete=1,
            delete_time=int(time.time())
        )
